package org.mayanjun.code.easyweb.springmvc.controller;

import org.apache.commons.lang.StringUtils;
import org.mayanjun.code.easyweb.common.Assert;
import org.mayanjun.code.easyweb.common.ServiceException;
import org.mayanjun.code.easyweb.common.Status;
import org.mayanjun.code.easyweb.springmvc.io.FileUploader;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 
 * @author mayanjun
 * @since 1.0.1(Jun 4, 2015)
 */
public abstract class UploadCapableController extends BaseController {

	protected String saveFile(MultipartFile file) {
		checkMultipartFile(file);
		String path;
		try {
			path = getFileUploader().saveFile(file.getInputStream(), getFileUploader().generateFileName(file.getOriginalFilename()));
		} catch (IOException e) {
			e.printStackTrace();
			throw new ServiceException(Status.INTERNAL_ERROR);
		}
		return path;
	}

	protected void checkMultipartFile(MultipartFile file) {
		Assert.notNull(file, "请选择文件");
		Assert.isTrue(!file.isEmpty(), "文件错误");
	}

	public abstract FileUploader getFileUploader();

	protected String saveFile(MultipartFile file, String fileName) {
		checkMultipartFile(file);
		String path;
		try {
			path = getFileUploader().saveFile(file.getInputStream(), fileName);
		} catch (IOException e) {
			e.printStackTrace();
			throw new ServiceException(Status.INTERNAL_ERROR);
		}
		return path;
	}
	
	protected void deleteFile(String path) {
		if(!StringUtils.isEmpty(path)) {
			getFileUploader().deleteFile(path);
		}
	}
	
}